import common from '../../utils/common.js'
import cookie from '../../utils/js-cookie'
import resetData from '../../utils/resetData.js'
var app = getApp();
Page({
  data: {
    tabFixed: false, //tab定位
    $toast: {
      show: false,
      text: ''
    },
    tab: {
      list: [{
        id: 'all',
        state: 1,
        title: '同班',
        book_lists: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
        beginrow: 0,
        islastline: 0,
        update: false,
        loading: false
      }, {
        id: 'topay',
        state: 2,
        title: '同级',
        book_lists: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
        beginrow: 0,
        islastline: 0,
        update: false,
        loading: false
      }, {
        id: 'tosend',
        state: 3,
        title: '同校',
        book_lists: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
        beginrow: 0,
        islastline: 0,
        update: false,
        loading: false
      }, {
        id: 'send',
        state: 4,
        title: '推荐',
        book_lists: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
        beginrow: 0,
        islastline: 0,
        update: false,
        loading: false
      }],
      selectedId: 'all',
      selectedIndex: 0,
      isaddschool: null
    },
    sliderItems: [],//首页轮播图
    imgSrc1: '',
    mask1_show: false,
    mask2_show: false,
    sing_state: false,
    book_currency: '',
    tabScrollTop: '',
    timesign: null //签到状态
  },
  searchChange(e) {
    this.setData({
      name: e.detail.value
    });
  },
  tabchange(e) {
    console.log(e, 999)
    let self = this
    let current = e.detail.selectedIndex
    let selectedId = e.detail.selectedId
    this.setData({
      [`tab.selectedIndex`]: current,
      [`tab.selectedId`]: selectedId
    }, function () {
      if (!self.data.tab.list[`${current}`].update) {
        self.getBook()
      }
    })
  },
  getBook(beginrow) {
    wx.showNavigationBarLoading()
    let self = this
    let selectedIndex = self.data.tab.selectedIndex
    let tab = self.data.tab
    let list = tab.list[`${selectedIndex}`]
    beginrow = beginrow || (list[`beginrow`])
    setTimeout(() => {
      app.getApi.getbook({
        state: list[`state`],
        beginrow: beginrow,
        pagecount: 12,
        token: app.globalData.token
      }).then(res => {
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh(); //停止下拉刷新
        if (beginrow == 0) { //初始化
          list.book_lists = res.data
          list.update = true
          tab.isaddschool = res.isaddschool
        } else {
          list.book_lists = list.book_lists.concat(res.data)
        }
        list.islastline = res.islastline
        list.beginrow = beginrow
        list.loading = false
        self.setData({
          tab: tab
        })
      })
    }, 500)
  },
  getplaypic() {
    let self = this
    app.getApi.getplaypic({}).then(res => {
      if (res.code == 3000) {
        self.setData({ 'sliderItems': res.data })
      }
    }).then(() => {
      self.getBook()
    })
  },
  bindchange(e) {
    if (e.detail.source != "touch") {
      return
    }
    let self = this
    let current = e.detail.current
    let id = this.data.tab.list[`${current}`].id
    this.setData({
      [`tab.selectedIndex`]: current,
      [`tab.selectedId`]: id
    }, () => {
      if (!self.data.tab.list[`${current}`].update) {
        self.getBook()
      }
    })
  },
  onMyEvent() {
    wx.navigateTo({
      url: '../search/index'
    })
  },
  tocreatetime() {
    let self = this
    app.getToken(token => {
      app.getApi.tocreatetime({ token: token }).then(res => {
        if (res.code == 3000) {
          self.setData({
            book_currency: res.data.book_currency,
            sing_state: true
          })
        }
      })
    })
  },
  goDetail(e) {
    console.log(e)
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `../detail/index?id=${id}`,
    })
  },
  updasign(cb) {
    let self = this
    let show_mask1 = false
    let mytime = common.getTime()
    cookie.getCookie('fist_guid_2', (res) => {
      show_mask1 = common.DateDiff(mytime, res) >= 1 ? true : false
    }, (res) => {
      show_mask1 = true
    })
    app.getToken(token => {
      app.getApi.updasign({ token: token }).then(res => {
        if (res.code == 3000) {
          cookie.getCookie('fist_guid', (res1) => {
            if (show_mask1) {
              self.setData({ //0：未签到；1：已经签到。
                mask1_show: !res.data.timesign,
                timesign: res.data.timesign
              })
            } else {
              self.setData({ //0：未签到；1：已经签到。
                timesign: res.data.timesign
              })
            }
          }, () => {
            self.setData({
              timesign: res.data.timesign
            })
            console.log('cookie失败', )
          })

          typeof cb == 'function' && cb()
        } else {
          common.showToast(self, res.message)
        }
      })
    })
  },
  scan() {
    common.scan(this, common)
  },
  addSchool() {
    wx.reLaunch({
      url: '../myinfo/index?fromPage=index',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let self = this
    let query = wx.createSelectorQuery();
    query.select('#nav').boundingClientRect(function (res) {
      console.log(res)
      self.setData({ 'tabScrollTop': res.top || 187 }, () => {
        self.updasign(self.getplaypic())
      })
    }).exec();
    cookie.getCookie('fist_guid', (res) => {
    }, () => {
      self.setData({
        mask2_show: true
      })
      console.log('cookie失败', )
    })
  },
  onPageScroll(obj) {
    let self = this;
    if (!self.data.tabFixed && obj.scrollTop >= self.data.tabScrollTop) {
      self.setData({ tabFixed: true })
    }
    if (self.data.tabFixed && obj.scrollTop < self.data.tabScrollTop) {
      self.setData({ tabFixed: false })
    }
  },
  closeGuide() {
    let self = this
    cookie.setCookie('fist_guid', 1)
    self.setData({ //0：未签到；1：已经签到。
      mask1_show: !self.data.timesign
    })
  },
  closeGuide2() {
    let self = this
    cookie.setCookie('fist_guid_2', common.getTime())
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let self = this
    if (this.data.tab.isaddschool == 0) {
      app.getToken(token => {
        app.getApi.isaddschool({ token: token }).then(res => {
          if (res.code == 3000) {
            if (res.data.isaddschool) {
              self.setData({
                tab: common.deepClone(resetData.tabIndex)
              }, () => {
                self.updasign(self.getplaypic())
              })
            }
          } else {
            common.showToast(self, res.message)
          }
        })
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let self = this
    self.setData({
      tab: common.deepClone(resetData.tabIndex)
    }, () => {
      self.updasign(self.getplaypic())
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let self = this
    let selectedIndex = self.data.tab.selectedIndex
    let list = self.data.tab.list[`${selectedIndex}`]
    if (list.loading || list.islastline) { //是否到底(0：否，1：是)
      return
    }
    this.setData({
      [`tab.list[${selectedIndex}].loading`]: true
    }, () => {
      let beginrow = self.data.tab.list[`${selectedIndex}`][`beginrow`]
      self.getBook(beginrow + 12)
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '天天享读，让图书传递爱',
      imageUrl: '../../assets/images/index_s.png',
      path: '/pages/index/index'
    }
  }
})